package com.dy.yunying.biz.controller.manage;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.dy.yunying.api.constant.ChannelPackTypeEnum;
import com.dy.yunying.api.dto.ChannelManageDto;
import com.dy.yunying.api.entity.ChannelManageDO;
import com.dy.yunying.api.entity.WanGameChannelInfoDO;
import com.dy.yunying.api.entity.WanGameChannelPlatformDO;
import com.dy.yunying.api.req.*;
import com.dy.yunying.api.vo.WanChannelPackPageVO;
import com.dy.yunying.api.vo.WanChannelPackVO;
import com.dy.yunying.api.vo.WanGameVersionVO;
import com.dy.yunying.biz.service.manage.*;
import com.pig4cloud.pig.admin.api.dto.UserInfo;
import com.pig4cloud.pig.admin.api.feign.RemoteUserService;
import com.pig4cloud.pig.admin.api.vo.UserSelectVO;
import com.pig4cloud.pig.common.core.constant.CommonConstants;
import com.pig4cloud.pig.common.core.constant.SecurityConstants;
import com.pig4cloud.pig.common.core.constant.enums.PlatformTypeEnum;
import com.pig4cloud.pig.common.core.exception.BusinessException;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.log.annotation.SysLog;
import com.pig4cloud.pig.common.security.service.PigUser;
import com.pig4cloud.pig.common.security.util.SecurityUtils;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 游戏渠道分包
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/pack")
@Api(value = "pack", tags = "游戏渠道分包")
public class GameChannelPackController {

	private static Logger logger = LoggerFactory.getLogger(GameChannelPackController.class);

	private final GameChannelPackService gameChannelPackService;

	private final GameService gameService;

	private final ChannelManageService channelManageService;

	private final AdRoleUserService adRoleUserService;

	private final RemoteUserService remoteUserService;

	private final GameChannelPlatformService gameChannelPlatformService;

	@Autowired
	private WanGameChannelInfoService wanGameChannelInfoService;

	/**
	 * 分页查询渠道包
	 *
	 * @return
	 */
	@SysLog("渠道分包列表")
	@RequestMapping("/page")
	public R page(@RequestBody WanChannelPackReq req) {
		try {
			List<UserSelectVO> userList = adRoleUserService.getOwnerRoleUsers();
			List<Integer> userIdList = userList.stream().map(UserSelectVO::getUserId).collect(Collectors.toList());
			req.setUserList(userIdList);
			if (null != req.getAppchlArr() && req.getAppchlArr().length > 0) {
				List<String> appchlList = new ArrayList<String>();
				Collections.addAll(appchlList, req.getAppchlArr());
				req.setAppchlList(appchlList);
			}
			IPage<WanChannelPackPageVO> data = gameChannelPackService.page(req);
			return R.ok(data, "查询成功");
		} catch (Exception e) {
			logger.error("分页查询渠道包异常：", e);
			return R.failed("查询失败");
		}
	}

	/**
	 * 修改分包渠道编码名称
	 */
	@SysLog("修改分包渠道编码名称")
	@GetMapping("/updateCodeName")
	public R page(String code, String codeName) {
		try {
			if (StringUtils.isBlank(codeName)) {
				return R.failed("分包编码名称为空");
			}
			if (Objects.isNull(code)) {
				return R.failed("分包Id为空，编辑失败");
			}
			if (StringUtils.isNotBlank(codeName)) {
				if (codeName.trim().length() > 20) {
					return R.failed("请输入20个字符以内的包名称");
				}
			}
			// 判断包名是否唯一  要确保包名唯一
			List<WanGameChannelInfoDO> list = gameChannelPackService.queryPkByCodeName(codeName, code);
			if (ObjectUtils.isNotEmpty(list)) {
				return R.failed("包名称重复、编辑失败");
			}
			WanGameChannelInfoDO wanGameChannelInfoDO = new WanGameChannelInfoDO();
			wanGameChannelInfoDO.setChl(code);
			wanGameChannelInfoDO.setCodeName(codeName);
			return wanGameChannelInfoService.updateCodeName(wanGameChannelInfoDO);
		} catch (Exception e) {
			logger.error("分页查询渠道包异常：", e);
			return R.failed("查询失败");
		}
	}

	/**
	 * 分包
	 *
	 * @return
	 */
	@SysLog("分包")
	@RequestMapping(value = "/pack", method = RequestMethod.POST)
	public R pack(@RequestBody GameChannelPackReq gameChannelPackReq) {
		try {
			// channelId、gameId、fromNum、toNum
			PigUser user = SecurityUtils.getUser();
			R<UserInfo> userinfoR = remoteUserService.info(user.getUsername(), SecurityConstants.FROM_IN);

			Long gameId = gameChannelPackReq.getGameId();
			String parentCode = gameChannelPackReq.getParentCode();

			Integer packNumFrom = gameChannelPackReq.getPackNumFrom();
			Integer packNumTo = gameChannelPackReq.getPackNumTo();
			Integer packType = gameChannelPackReq.getPackType();

			// 参数校验
			if (null == user || gameId == null || null == packType || StringUtils.isBlank(parentCode) || packNumFrom == null || packNumTo == null || packNumFrom <= 0 || packNumFrom > packNumTo) {
				return R.failed("参数不合法");
			}
			//校验推广类型
			if (null != gameChannelPackReq.getSpreadType() && 2 == gameChannelPackReq.getSpreadType()) {
				if (StringUtils.isBlank(gameChannelPackReq.getSettleType())) {
					return R.failed("推广类型为短视频时，推广方式必填");
				}
			}else{
				gameChannelPackReq.setSettleType(null);
			}
			WanGameVersionVO game = gameService.selectVersionVOByPK(gameId, packType);
			// 参数校验
			if (game == null) {
				return R.failed("参数不合法");
			}
			if (game.getVersionId() == null) {
				return R.failed("当前游戏没有上传基本包");
			}
			ChannelManageDO parentChannel = channelManageService.getOne(Wrappers.<ChannelManageDO>query().lambda().eq(ChannelManageDO::getChncode, parentCode).eq(ChannelManageDO::getPid, 0).last("limit 1"));
			if (parentChannel == null) {
				return R.failed("参数不合法");
			}
			if(PlatformTypeEnum.GDT.getValue().equals(parentChannel.getPlatform().toString())){
				if (null != gameChannelPackReq.getSpreadType() && 2 == gameChannelPackReq.getSpreadType()) {
					return R.failed("广点通无法选择短视频");
				}
			}
			//查询创建子渠道，如果自身有子渠道，则直接查询，没有的话，则创建
			ChannelManageDO channel = channelManageService.getOne(Wrappers.<ChannelManageDO>query().lambda().eq(ChannelManageDO::getParentCode, parentCode)
					.eq(ChannelManageDO::getPackUserid, user.getId()).ne(ChannelManageDO::getPid, 0).last("limit 1"));
			//不存在，则创建
			if (channel == null) {
				ChannelManageDto channelManageDto = new ChannelManageDto();
				channelManageDto.setPid(parentChannel.getId());
				channelManageDto.setParentCode(parentCode);
				//使用登录名作为子渠道名称
				if (userinfoR.getCode() == CommonConstants.SUCCESS) {
					channelManageDto.setChnname(userinfoR.getData().getSysUser().getRealName());
				} else {
					channelManageDto.setChnname(user.getUsername());
				}

				//子渠道的分包用户需要生成
				channelManageDto.setPackUserid(user.getId());
				channelManageDto.setChncode("temp");
				channelManageDto.setManage(Long.valueOf(user.getId()));
				channelManageDto.setPlatform(parentChannel.getPlatform());
				channelManageDto.setIsDefault(0);
				channelManageDto.setIsup(1);
				R r = channelManageService.savechl(channelManageDto);
				if (r.getCode() == CommonConstants.SUCCESS) {
					channel = JSON.parseObject(JSON.toJSONString(r.getData()), ChannelManageDO.class);
				} else {
					return R.failed(r.getMsg());
				}
			}
			//赋值子渠道
			gameChannelPackReq.setChlId(channel.getId());
			gameChannelPackReq.setVersionId(game.getVersionId());
			gameChannelPackReq.setType(ChannelPackTypeEnum.CHANNEL.getType());
			gameChannelPackService.pack(gameChannelPackReq);
			return R.ok();
		} catch (BusinessException e) {
			logger.error("生成渠道包异常：", e);
			return R.failed(e.getMessage());
		} catch (Exception e) {
			logger.error("生成渠道包异常：", e);
		}
		return R.failed("操作失败");
	}

	/**
	 * 投放管理 / 联调管理 / 渠道参数配置
	 * 生成渠道参数
	 *
	 * @return
	 */
	@SysLog("生成渠道参数")
	@RequestMapping(value = "/packBase", method = RequestMethod.POST)
	public R packBase(@RequestBody GameBasePackReq req) {
		try {
			Integer userId = SecurityUtils.getUser().getId();
			Long gameId = req.getGameId();
			Integer parentChlId = req.getParentChlId();
			Long appId = req.getAppId();
			String platform = req.getPlatformId();

			// 参数校验
			if (userId == null || gameId == null || parentChlId == null || appId == null || StringUtils.isBlank(platform)) {
				return R.failed("参数不合法");
			}
			if (!PlatformTypeEnum.TT.getValue().equals(platform)){
				if (StringUtils.isBlank(req.getAppName())){
					return R.failed("AppName不能为空");
				}
			}

			if (StringUtils.isNotBlank(req.getAppName())){
				req.setAppName(req.getAppName().replaceAll(" +",""));
			}

			//设置为空,  生成渠道参数的时候，目前不让查询的到
			//req.setCreator(String.valueOf(SecurityUtils.getUser().getId()));
			gameChannelPackService.packBase(req);

			return R.ok();
		} catch (BusinessException e) {
			logger.error("生成渠道包异常：", e);
			return R.failed(e.getMessage());
		} catch (Exception e) {
			logger.error("生成渠道包异常：", e);
		}
		return R.failed();
	}

	/**
	 * 更新渠道参数信息
	 *
	 * @param req
	 * @return
	 */
	@SysLog("更新渠道参数信息")
	@RequestMapping(value = "/editChannelPlatform")
	public R editChannelPlatform(@RequestBody GameBasePackReq req) {
		if (Objects.isNull(req.getGameId())) {
			return R.failed("未获取到游戏ID");
		}
		if (StringUtils.isBlank(req.getPlatformId())) {
			return R.failed("未获取到平台ID");
		}
		if (StringUtils.isBlank(req.getGdtAppid())) {
			return R.failed("未获取到广点通APPID");
		}
		if (!isNum(req.getGdtAppid())) {
			return R.failed("广点通APPID为数字组成");
		}
		WanGameChannelPlatformDO channelPlatformDO = new WanGameChannelPlatformDO();
		channelPlatformDO.setGameid(req.getGameId().intValue());
		channelPlatformDO.setPlatformid(Integer.valueOf(req.getPlatformId()));
		channelPlatformDO.setGdtAppid(req.getGdtAppid());
		WanGameChannelPlatformDO gameChannelPlatformDO = gameChannelPlatformService.saveByUK(channelPlatformDO);
		return R.ok(gameChannelPlatformDO);
	}

	/**
	 * 更新分包
	 * 使用子游戏最新基础包更新渠道编码的分包
	 *
	 * @return
	 */
	@SysLog("更新分包")
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public R update(@RequestBody GameChannelPackUpdateReq req) {
		try {
			Long packId = req.getPackId();

			// 参数校验
			if (packId == null) {
				return R.failed("参数不合法");
			}
			req.setCreator(String.valueOf(SecurityUtils.getUser().getId()));
			gameChannelPackService.update(req);

			return R.ok();
		} catch (BusinessException e) {
			logger.error("生成渠道包异常：", e);
			return R.failed(e.getMessage());
		} catch (Exception e) {
			logger.error("生成渠道包异常：", e);
		}
		return R.failed();
	}

	/**
	 * 获取分包最新版本列表
	 *
	 * @param req
	 * @return
	 */
	@RequestMapping("/latestList")
	public R latestList(@RequestBody WanChannelPackReq req) {
		try {
			if (Objects.isNull(req.getGameId())) {
				return R.failed("子游戏ID不能为空");
			}
			if (StringUtils.isBlank(req.getParentCode())) {
				return R.failed("主渠道不能为空");
			}
			if (Objects.isNull(req.getPackType())) {
				return R.failed("请选择母包类型");
			}
			req.setSize(999);
			req.setPackUserid(String.valueOf(SecurityUtils.getUser().getId()));
			List<WanChannelPackVO> list = gameChannelPackService.latestList(req);
			return R.ok(list);
		} catch (BusinessException e) {
			logger.error("获取分包列表异常：", e);
			return R.failed();
		} catch (Exception e) {
			logger.error("获取分包列表异常：", e);
		}
		return R.failed();
	}

	/**
	 * 获取角色平台账号的最新分包列表
	 *
	 * @param req
	 * @return
	 */
	@RequestMapping("/myRoleLatestList")
	public R myRoleLatestList(WanChannelPackReq req) {
		try {
			req.setPackUserid(null);
			req.setSize(999);
			List<WanChannelPackVO> list = gameChannelPackService.latestList(req);
			return R.ok(list);
		} catch (Throwable e) {
			logger.error("获取分包列表异常：", e);
		}
		return R.failed();
	}

	/**
	 * 分包编码 查询对应分包名称
	 */
	@RequestMapping("/queryAppChlName")
	public R queryAppChlName(List<String> appChlArr) {
		try {
			List<Map<String, String>> appChlList = gameChannelPackService.queryAppChlName(appChlArr);
			return R.ok(appChlList);
		} catch (Throwable e) {
			logger.error("获取分包名称异常：", e);
		}
		return R.failed();
	}

	public static boolean isNum(String str) {

		Pattern pattern = Pattern.compile("^-?[0-9]+");
		if (pattern.matcher(str).matches()) {
			//数字
			return true;
		} else {
			//非数字
			return false;
		}
	}


	/**
	 * 分页查询cps渠道包
	 *
	 * @return
	 */
	@SysLog("cps渠道分包列表")
	@RequestMapping("/cps/page")
	@PreAuthorize("@pms.hasPermission('cps_pack_page')")
	public R cpsPage(@RequestBody WanChannelCpsPackReq req) {
		try {
			List<UserSelectVO> userList = adRoleUserService.getOwnerRoleUsers();
			List<Integer> userIdList = userList.stream().map(UserSelectVO::getUserId).collect(Collectors.toList());
			req.setUserList(userIdList);
			IPage<WanChannelPackPageVO> data = gameChannelPackService.cpsPage(req);
			return R.ok(data, "查询cps渠道包成功");
		} catch (Exception e) {
			logger.error("分页查询cps渠道包异常：", e);
			return R.failed("查询失败");
		}
	}



	/**
	 * cps分包
	 *
	 * @return
	 */
	@SysLog("cps分包")
	@RequestMapping(value = "/cps/pack", method = RequestMethod.POST)
	@PreAuthorize("@pms.hasPermission('cps_channel_pack')")
	public R cpsPack(@RequestBody GameChannelPackReq gameChannelPackReq) {
		try {
			Long gameId = gameChannelPackReq.getGameId();
			String parentCode = gameChannelPackReq.getParentCode();

			Integer packNumFrom = gameChannelPackReq.getPackNumFrom();
			Integer packNumTo = gameChannelPackReq.getPackNumTo();
			// 母包类型：1-运营母包；2-云微端；  ps : cps分包默认使用运营母包
			gameChannelPackReq.setPackType(1);
			// 参数校验
			if (gameId == null){
				return R.failed("子游戏不能为空");
			}
			if (StringUtils.isBlank(parentCode)){
				return R.failed("主渠道不能为空");
			}
			if (gameChannelPackReq.getChlId() == null){
				return R.failed("子渠道不能为空");
			}
			if (packNumFrom == null || packNumTo == null || packNumFrom <= 0 || packNumFrom > packNumTo) {
				return R.failed("参数不合法");
			}
			WanGameVersionVO game = gameService.selectVersionVOByPK(gameId, gameChannelPackReq.getPackType());
			// 参数校验
			if (game == null) {
				return R.failed("参数不合法");
			}
			if (game.getVersionId() == null) {
				return R.failed("当前游戏没有上传基本包");
			}
			ChannelManageDO parentChannel = channelManageService.getOne(Wrappers.<ChannelManageDO>query().lambda().eq(ChannelManageDO::getChncode, parentCode).eq(ChannelManageDO::getPid, 0).last("limit 1"));
			if (parentChannel == null) {
				return R.failed("参数不合法");
			}
			//赋值子渠道
			gameChannelPackReq.setChlId(gameChannelPackReq.getChlId());
			gameChannelPackReq.setVersionId(game.getVersionId());
			gameChannelPackReq.setType(ChannelPackTypeEnum.CHANNEL.getType());
			gameChannelPackService.cpsPack(gameChannelPackReq);
			return R.ok();
		} catch (BusinessException e) {
			logger.error("生成cps渠道包异常：", e);
			return R.failed(e.getMessage());
		} catch (Exception e) {
			logger.error("生成cps渠道包异常：", e);
		}
		return R.failed("操作失败");
	}

}
